package com.frozenc.controller.auth;

import com.frozenc.Util.CryptUtil;
import com.frozenc.domain.User;
import com.frozenc.enums.UserType;
import com.frozenc.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * Created by FrozenC on 2016/9/9.
 */
@Controller
public class SignIn {
    @Autowired
    UserMapper userMapper;

    @ModelAttribute
    public void setUser(HttpSession session,ModelMap modelMap){
        User user = (User) session.getAttribute("currUser");
        modelMap.addAttribute("currUser",user);
        return ;
    }

    @RequestMapping(value = "/signin",method = RequestMethod.GET)
    public String Get() {
        return "signin";
    }

    @RequestMapping(value = "/signin",method = RequestMethod.POST)
    @ResponseBody
    public String Post(@RequestBody @Valid User user, ModelMap modelMap,HttpSession httpSession) {

        User userDAO = null;
        try {
            userDAO = userMapper.selectByUsername(user.getUsername());

            if(userDAO == null){
                return "用户名或密码错误";
            }

            String exactPwd = CryptUtil.getSHA1(user.getPassword(),userDAO.getSalt());
            if(!exactPwd.equals(userDAO.getPassword())){
                return "用户名或密码错误";
            }
        } catch (DataAccessException e) {
            String errMsg = e.getMessage();
            System.out.println(errMsg);
            return "未知错误";
        }

        httpSession.setAttribute("currUser",userDAO);
        return "ok";
    }
}
